03 / 07

What is protected? How is it different from private and public?

Difficulty: 2/10

protected vs private vs public

Protected provides controlled visibility between private implementation details and a completely public API. It generally allows access from the declaring class and derived classes, but the exact rules differ between Java and C#. Private is more restrictive and is intended for implementation details of the declaring type. Public exposes the member as part of the externally accessible API. In Java, protected also has package-level access semantics, which makes it broader than simply 'subclasses only'.

javascript
  1. 1

    private: strongest normal member-level encapsulation.

  2. 2

    protected: exposes a member to the declaring type and appropriate subclasses.

  3. 3

    public: exposes the member broadly according to the language's accessibility model.

  4. 4

    Java protected additionally provides access within the same package.

  5. 5

    Protected members can increase coupling between a base class and subclasses.

Follow-up Questions

  • Can protected members be accessed outside a package in Java?
  • Why should protected fields be used carefully?
  • Can a private member be accessed through inheritance?
  • What is the difference between protected and internal?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.